using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Magiq.Databases.Insert
{
    public class InsertCommandBuilder : DynamicSelectCommandBuilder
    {
        public InsertCommandBuilder(Type elementType, IOrmAdapter ormAdapter, IQueryable where,
                                    IEnumerable<InsertColumnsAssignment> assignments)
            : base(ormAdapter, where, assignments, false)
        {
            Init(elementType);
        }

        public override IDbCommand GetCommand()
        {
            var values = BaseSelectedValues;
            var columns = Columns;

            var columnValues = new Dictionary<string, string>();
            var baseIndex = values.Length - columns.Length;
            
            for (var i = 0; i < columns.Length; i++)
                columnValues.Add(columns[i], values[i+baseIndex]);

            Command.CommandText = OrmAdapter.Dialect.InsertClauseFor(BaseTableName, columnValues, From);
            return Command;
        }
    }
}